package com.gxgeek.javabasic.collection.map;

import java.util.ArrayList;
import java.util.List;
import java.util.WeakHashMap;

/**
 * @author gaoxing
 * @create 2018-06-06 下午5:17
 */
public class AnalyzeWeakHashMap {
    public static void main(String[] args) throws Exception {
//        test1();
//        test2();

//        test3();
//
        test4();


    }

    private static void test4() {
        List<WeakHashMap<byte[][], byte[][]>> maps = new ArrayList<WeakHashMap<byte[][], byte[][]>>();
        for (int i = 0;; i++) {
            WeakHashMap<byte[][], byte[][]> d = new WeakHashMap<byte[][], byte[][]>();
            d.put(new byte[10000][10000], new byte[10000][10000]);
            maps.add(d);
            System.gc();
            // 关键 -> 区别：
//            System.err.print(i+"，");

            System.err.println(  "size = " + d.size());

            // 输出结果：
            // size = 0
            // ...
        }
    }

    private static void test3() {
        List<WeakHashMap<byte[][], byte[][]>> maps = new ArrayList<WeakHashMap<byte[][], byte[][]>>();
        for (int i = 0;; i++) {
            WeakHashMap<byte[][], byte[][]> d = new WeakHashMap<byte[][], byte[][]>();
            d.put(new byte[10000][10000], new byte[10000][10000]);
            maps.add(d);
            System.gc();
            System.err.print(i+"，");

            // 输出结果：
            // 0，1，2，3，4，5，6，7，8，9，10，
            // Exception in thread "main" java.lang.OutOfMemoryError: Java heap space at Test3.main(Test3.java:10)
        }
    }

    private static void test2() throws InterruptedException {
        WeakHashMap<Object, String> wmap = new WeakHashMap<Object, String>();
        wmap.put(new Object(), "a");
        System.gc();
        Thread.sleep(100);
        System.out.println(wmap.size());
        // 输出结果：0
    }

    private static void test1() throws InterruptedException {
        WeakHashMap<Object, String> wmap = new WeakHashMap<Object, String>();
        wmap.put(null, "a");
        System.gc();
        Thread.sleep(100);
        System.out.println(wmap.size());
        // 输出结果：1
    }

}
